<template>
  <div>
  <div  class="header-tool">
  

    <a-input-search
        style="width: 300px; margin-right: 10px"
        v-model:value="searchValue"
        placeholder="请输入手机号搜索"
         @search="onSearch"
      />
      <a-button
        style="margin-right: 20px"
        class="mr10"
        type="primary"
        enter-button
        @click="onSearch()"
      >
        搜索
      </a-button>

    
      <a-button
      class="mr10"
      type="primary"
      @click="reLoad()"
    >
      刷新
    </a-button>
 
    </div>

    <a-table
      :row-key="(record) => record.news_id"
      :rowSelection="{
        onChange: onSelectChange,

        selectedRowKeys: mapRows
      }"
      :columns="newColumns"
      :dataSource="activities"
         @change="handleTableChange"
      :pagination="
        isObject(pagination)
          ? {
              showQuickJumper: true,
              total: pagination.total,
              current: pagination.current,
              pageSize: pagination.pageSize,
              showTotal: (total) => `共计 ${pagination.total} 条`
            }
          : false
      "
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'prize_name'">
        {{ record.Raffle.prize_name }}
        </template>
        <template v-if="column.dataIndex === 'prize_image'">
          <img
            style="width: 50px; height: 50px"
            :src="record.Raffle.prize_image"
          />
        </template>
        <template v-if="column.dataIndex === 'user'">
          <div style="    display: flex;
    align-items: center;">

         
          <img :src="record.User.avatar" style="width: 30px;height: 30px;border-radius:50% ;" />
        <span style="    margin-left: 10px;"> {{ record.User.user_name }}  </span>
      </div> 
      </template>
        <template v-if="column.dataIndex === 'phone'">
        {{ record.User.phone }}  
        </template>
        <template v-if="column.dataIndex === 'address'">
        {{ record?.address?.consignee }} - {{ record?.address?.phone }} <br>
        {{ record?.address?.province }}  {{ record?.address?.city }}  {{ record?.address?.district }} {{ record?.address?.house }} 
        </template>


      
        <template v-if="column.dataIndex === 'action'">
          <span>
            <a @click="postSend(record)" v-if="record?.address&&record?.address?.address_id&&!record?.tracking_number">发货</a>
            <a @click="postSend(record,'edit')" v-if="record?.address&&record?.address?.address_id&&record?.tracking_number">改物流单号</a>
            <a-divider type="vertical" />
            <a @click="LogisticsEvent(record)" v-if="record?.tracking_number">查看物流</a>

            
          </span>
        </template>
      </template>
    </a-table>

    <raffleForm
      ref="newsFormEle"
      :showAddDialog="showAddDialog"
      @success="handleActivityAdded"
      @close="showAddDialog = false"
    />
    <deliverGoods
      ref="deliverGoodsRef"
      @refuData="refuData"
    ></deliverGoods>
    <Logistics ref="LogisticsRef"></Logistics>
  </div>
</template>

<script setup>
  import { isObject } from 'lodash-es'
  import { message } from 'ant-design-vue'
  import deliverGoods from './../comm/deliverGoods.vue'
  import Logistics from './../comm/Logistics.vue'
  import { ref, onMounted, reactive, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElButton, ElTable, ElTableColumn, ElDialog } from 'element-plus'
  import raffleForm from './raffleForm.vue'
  import { raffleLog, raffleDel, raffleUpdate, rafflePoint } from '@/api/index'
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const LogisticsRef = ref(null)
  const deliverGoodsRef = ref(null)
  const raffle = ref(null)
  const activities = ref([])
  const newColumns = [
    {
      title: 'id',
      dataIndex: 'raffle_id',
      key: 'ID'
    },
    {
      title: '奖品名称',
      dataIndex: 'prize_name',
      key: 'prize_name'
    },
    {
      title: '奖品图片',
      dataIndex: 'prize_image',
      key: 'prize_image'
    },
    {
      title: '中奖用户',
      dataIndex: 'user',
       
    },
    {
      title: '联系方式',
      dataIndex: 'phone',
 
    },
    {
      title: '中奖时间',
      dataIndex: 'created_at',
      key: 'created_at'
    },
    {
      title: '收货信息',
      dataIndex: 'address',
     
    },
    {
      title: '物流单号',
      dataIndex: 'tracking_number',
     
    },
    
    // {
    //   title: '上架',
    //   dataIndex: 'del',
    //   key: 'del'
    // },
   
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action'
    }
  ]
  const columns = [
    { id: 'ID' },
    { title: '标题' },
    { image: '主图' },
    { fav_num: '收藏' },
    { is_del: '上架' },
    { created_at: '创建时间' },
    {
      action: {
        title: '操作',
        width: '90px'
      }
    }
  ]
  const mapRows = ref([])
  const onSelect = () => {}
  const onSelectAll = () => {}
  const onSelectChange = (selectedRowKeys, selectedRows) => {
    mapRows.value = selectedRowKeys
  }
  const LogisticsEvent = (row) => {
    LogisticsRef.value.init( row.tracking_number,row.address.phone)
  }
  const saveRaffle = () => {
    rafflePoint({
      point: raffle.value
    }).then((res) => {
      if(res.errorCode){
        message.error(res.msg||'操作失败')
        return
      }
      message.success('设置成功')
    })
  }
  const batchLoading = (status) => {
    if (mapRows.value.length == 0) {
      message.error('请选择要操作的项')
      return
    }
    console.log(mapRows.value)

    newsIsDestroy({ news_id: mapRows.value, is_del: status == 1 ? true : false }).then((res) => {
      if(res.errorCode){
        message.error(res.msg||'操作失败')
        return
      }
      getList()
    })
  }
  const newsFormEle = ref()
  const showAddDialog = ref(false)
  const router = useRouter()
  const isFetching = ref(false)
  const searchValue = ref("")
  const onSearch = () => {
    pagination.current = 1
    getList()
  }
  const getList = () => {
    raffleLog({
      page: pagination.current,
      phone: searchValue.value,
      pageSize: pagination.pageSize
    })
      .then((res) => {
        if(res.errorCode){
        message.error(res.msg||'操作失败')
        return
      }
      res.data.map(val=>val.address=JSON.parse(val.address))
        activities.value = res.data

        if (res.data.length > 0) {
          raffle.value = res.data[0].point
        }
        pagination.total = res.total
      })
      .catch((err) => {
        console.log(err)
      })
  }
  getList()
  const reLoad = () => {
    pagination.current = 1
    getList()
  }
  const refuData = () => {
   
    getList()
  }
  const handleTableChange = ({ current, pageSize }) => {
    pagination.current = current
    pagination.pageSize = pageSize
    getList()
  }
  // 发货
  const postSend = (row,type) => {
    deliverGoodsRef.value.init(row,'raffle',type)
  }
  const changeDel = (e, row) => {
    raffleUpdate({ raffle_id: row.raffle_id, del: e })
      .then((res) => {
        if(res.errorCode){
          row.is_del = !e
        message.error(res.msg||'操作失败')
        return
      }
        getList() // Refresh activity list after deletion
      })
      .catch((error) => {
        row.is_del = !e
      })
  }
  const handleDelete = (row) => {
    raffleDel({ raffle_id: row.raffle_id })
      .then((res) => {
        if(res.errorCode){
        message.error(res.msg||'操作失败')
        return
      }
        getList() // Refresh activity list after deletion
      })
      .catch((error) => {
        console.error('Error deleting activity:', error)
      })
  }

  const handleActivityAdded = () => {
    getList() // Refresh activity list after adding
    showAddDialog.value = false // Close the dialog
  }

  // onMounted(fetchActivities);
</script>

<style scoped>
  .header-tool {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 10px;
  }

  .header-tool button {
    margin-right: 5px;
  }
</style>
